<?php

namespace app\admin\controller;

use app\common\service\WXUtils;

class Adminuser extends Admin
{
	public function __construct()
	{
		parent::__construct();
		$this->model = 'AdminUser';
		$this->assign("model", "AdminUser");
		$this->assign("modelPk", "userid");
	}

	public function get_where_map()
	{
		$keywords = input('param.keywords');
		$roleid = input('param.roleid');
		$dealer = input('param.dealer');
		$dealerid = input('param.dealerid/d');
		$isvip = input('param.isvip/s');
		$whereDatas = [];

		if ($dealer) {
			if ($this->uinfo['roleid'] == 1) {
				$whereDatas['roleid'] = 6;
			}
		} else {
			if ($this->uinfo['roleid'] == 1) {
				$whereDatas['roleid'] = ['neq', 6];
			}
		}
		if ($roleid) {
			$whereDatas['roleid'] = $roleid;
		}
		if ($dealerid) {
			$whereDatas['dealerid'] = $dealerid;
		} else {
			if ($this->uinfo['roleid'] == 4) {
				if ($dealer) {
					$whereDatas['roleid'] = 6;
				} else {
					$dealerids = model('AdminUser')->where('puserid', $this->uinfo['userid'])->where('roleid', 6)->column('userid');
					$whereDatas['dealerid'] = ['in', $dealerids];
					if (!isset($whereDatas['roleid'])) {
						$whereDatas['roleid'] = ['neq', 6];
					}
				}
			} elseif ($this->uinfo['roleid'] == 6) {
				$whereDatas['dealerid'] = $this->uinfo['userid'];
			}
		}
		if ($isvip != '') {
			$whereDatas['vip'] = $isvip;
		}
		if ($keywords) {
			$whereDatas['userid|username|fullname|realname|phone'] = ['like', "%$keywords%"];
		}
		return $whereDatas;
	}
	public function index()
	{
		$where['status'] = 0;
		if ($this->uinfo['roleid'] == 1) {
			$where['roleid'] = 6;
		} elseif ($this->uinfo['roleid'] == 4) {
			$where['roleid'] = 6;
			$where['puserid'] = $this->uinfo['userid'];
		} elseif ($this->uinfo['roleid'] == 6) {
			$where['userid'] = $this->uinfo['userid'];
		}
		$deallist = model($this->model)->where($where)->order('userid desc')->column('userid, username');
		$this->assign('deallist', $deallist);
		$this->assign('authgroup', cache('AuthGroup'));
		return $this->fetch();
	}
	public function index_dealer()
	{

		$this->assign('editurl', url('edit_dealer'));
		return $this->fetch();
	}

	public function add()
	{
		$this->assign('authgroup', cache('AuthGroup'));
		return $this->fetch();
	}
	public function data_save()
	{
		$db = model($this->model);
		$postData = input("post.postData");
		parse_str($postData, $dataarr);
		if ((!isset($dataarr['roleid']) || $dataarr['roleid'] != 9) && (!isset($dataarr['puserid']) || !$dataarr['puserid'])) {
			$dataarr['puserid'] = $this->uinfo['userid'];
		}
		if ($this->uinfo['roleid'] == 6 && (!isset($dataarr['dealerid']) || !$dataarr['dealerid'])) {
			$dataarr['dealerid'] = $this->uinfo['userid'];
		}
		// trace($dataarr);
		$id = $db->save_data($dataarr);
		if ($id == -1) {
			return json(['status' => 0, 'msg' => '请选择销售总监']);
		} elseif ($id === false) {
			return json(['status' => 0, 'msg' => $db->getError()]);
		}
		model('MemberStatistics')->add_log();
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function index_stat()
	{

		return $this->fetch();
	}
	public function edit()
	{
		$items = input("param.items");
		$db = model($this->model);
		$info = $db::get(['userid' => $items]);
		$this->assign('authgroup', cache('AuthGroup'));
		$this->assign("info", $info);
		if ($info['roleid'] == 9 && $this->uinfo['roleid'] == 6) {
			return $this->fetch('edit_subord');
		} else {
			return $this->fetch();
		}
	}
	public function add_dealer()
	{
		$this->assign('authgroup', cache('AuthGroup'));
		return $this->fetch();
	}
	public function edit_dealer()
	{
		$items = input("param.items");
		$db = model($this->model);
		$info = $db::get(['userid' => $items]);
		$provinceid = model('City')->where('code', $info['city_code'])->value('pid');
		$this->assign("provinceid", $provinceid);
		$this->assign("info", $info);
		$this->assign('authgroup', cache('AuthGroup'));
		return $this->fetch();
	}
	//添加经纪人
	public function add_subord()
	{
		$this->assign('authgroup', cache('AuthGroup'));
		return $this->fetch();
	}
	//分配地区权限
	public function user_auth()
	{
		$where = [];
		if ($this->uinfo['roleid'] == 1) {
			$where['pid'] = 1;
		} else {
			$citylist = db('AdminAuth')->where('userid', $this->uinfo['userid'])->order('id desc')->group('province_code')->select();
			$citycodes = [];
			foreach ($citylist as $v) {
				$citycodes[] = $v['province_code'];
			}
			$where['code'] = ['in', $citycodes];
		}

		$list = model('City')->where($where)->order('id asc')->select();
		$this->assign("list", $list);
		return $this->fetch();
	}
	public function edit_pwd()
	{
		$userid = 1;
		$info = model("AdminUser")->where("userid = '$userid'")->field("username,userid")->find();
		$this->assign("info", $info);
		return $this->fetch();
	}
	public function edit_pwd_update()
	{
		$validate = validate("AdminUser");
		$postData = input("post.postData");
		parse_str($postData, $dataarr);
		if (!$validate->scene('edit_admin_pwd')->check($dataarr)) {
			$msg = $validate->getError();
			return json(['status' => 0, 'msg' => $msg]);
		}
		// $dataarr['password'] = md5($dataarr['password']);
		model("AdminUser")->isUpdate(true)->allowField(true)->save($dataarr);
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function data_delete()
	{
		$items = input("param.items");
		if (strpos($items, "1,") !== false) {
			return json(['status' => 0, 'msg' => '管理员[admin]不允许删除']);
		}
		$items = trim($items, ",");
		$model = input("param.model");

		$db = model($model);
		// $db->delete_data(['item_ids' => $items]);
		$db->where('userid', 'in', $items)->where('roleid', 'not in', [1, 6, 8, 9, 10, 11])->delete();
		$itemarr = explode(',', $items);
		model('MemberStatistics')->add_log(1, -count($itemarr));
		return json(['status' => 1, 'msg' => '操作成功']);
	}

	public function image()
	{
		$id = input('param.id');
		$path = $this->create_qrcode($id);
		$this->assign('path', $path);
		return $this->fetch();
	}

	// 获取小程序码
	private function create_qrcode($userid)
	{
		// 1、先查看此用户没有没推广二维码，如果有的话，就直接返回，没有的话，走第2步
		$bigmpqrcode = model('AdminUser')->where('userid', $userid)->value('bigmpqrcode');
		$dealerid = model('AdminUser')->where('userid', $userid)->value('dealerid');
		$arrQR = isset($bigmpqrcode) ? $bigmpqrcode : '';
		// if ($arrQR != '') {
		// 	return APP_URL . '/' . $bigmpqrcode;
		// }
		// 2、首先获取access_token
		$wxutils = new WXUtils();
		$access_token = $wxutils->getAccessToken();
		// return $access_token;
		// 3、获取带参数无限个数小程序码
		$dealerinfo = model('AdminUser')->where('userid', $dealerid)->where('roleid', '6')->field('userid as storeid, username, username, province_code')->find();
		// $provinceinfo = model('City')->where('code', $dealerinfo['province_code'])->value('title');
		$scene = $dealerinfo['province_code'] . ',' . $dealerinfo['storeid'];
		$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
		$arr = [
			'scene' => $scene,
			'page' => 'pages/login/register',
			'width' => 1280,
			'auto_color' => false,
		];
		$param_json = json_encode($arr);
		$data = curlPost($url, $param_json);
		// 4、将图片数据data存储到服务器并写入数据库
		$filename = md5('qrcode' . time() . rand(100, 999));
		$filepath = 'upload/4sqrcode/' . $filename . '.png';
		// trace('xxxxx');
		// trace($filepath);
		// 存储到服务器
		file_put_contents(ROOT_PATH . $filepath, $data);
		// 写入数据库
		model('AdminUser')->where('userid', $userid)->update(['bigmpqrcode' => $filepath]);
		return APP_URL . '/' . $filepath;
		// $file = fopen('qrcode_' . time() . '.jpg', $data); //打开文件准备写入
		// fwrite($file, $res); //写入,$res为图片二进制内容
		// fclose($file); //关闭

		// return $data;
	}

	public function append_coupons()
	{
		$whereDatas = ['auditstatus' => '1'];
		$roleid = $this->uinfo['roleid'];
		$userid = $this->uinfo['userid'];
		$targetuserid = input("param.userid/s");
		if ($roleid == 4) {
			$whereDatas['createrid'] = ['neq', '1'];
		} else if ($roleid !== 1) {
			$whereDatas['createrid'] = $userid;
		}
		//
		$list = model('Coupons')->where($whereDatas)->select();
		foreach ($list as $data) {
			if ($data['type'] == 'activity') {
				$data['type'] = '活动券';
			} else {
				$data['type'] = $data['type'] ? config('COUPONS_TYPE.' . $data['type']) : '未设置';
			}
		}
		$this->assign('lists', $list);
		$this->assign('userid', $targetuserid);
		return $this->fetch();
	}

	// 给某会员补发优惠券
	public function set_coupons()
	{
		$postData = input("post.postData");
        parse_str($postData, $dataarr);
		$couponsid = $dataarr['check_id'];
		$targetuserid = $dataarr['id'];
		// $userids = [$targetuserid];
		// trace($userids);
		exec_php('/index/cron/send_coupons', ['type' => 'append_again', 'couponsid' => $couponsid, 'userids' => $targetuserid]);

		exec_php('/index/cron/test');
		
		$file = '/home/wwwroot/web/domain/sijiawx/web/logs/command.log';
		$current = "set_coupons() success at ".date('Y-m-d H:i:s')."\n";
		file_put_contents($file, $current, FILE_APPEND);

        return json(['status' => 1, 'msg' => '操作成功']);
        // $userids = [];
        // if (isset($dataarr['check_userids'])) {
        //     $userids = $dataarr['check_userids'];
        // }
        // if ($couponsid) {
        //     model('CouponsUser')->where('couponsid', $couponsid)->delete();
        // }
        // $data = [];
        // foreach ($userids as $userid) {
        //     $a_data['couponsid'] = $couponsid;
        //     $a_data['userid'] = $userid;
        //     $data[] = $a_data;
        //     $a_data = [];
        // }
        // if ($data) {
        //     $id = model('CouponsUser')->save_data($data);
        //     if ($id === false) {
        //         return json(['status' => 0, 'msg' => '保存失败']);
        //     }
        // }
	}

	public function renew_user() {
//        $uinfo = model('AdminUser')->where('userid', '18970')->find();
//
//        // 判断是否是续费会员并记录续费次数
//        $vipendtime = $uinfo['vipendtime'];
//        if ($vipendtime > 0) { // 续费会员
//            model('AdminUser')->where('userid', '18970')->update(['viprenew' => $uinfo['viprenew'] + 1]);
//        }
        $where['status'] = 0;
        if ($this->uinfo['roleid'] == 1) {
            $where['roleid'] = 6;
        } elseif ($this->uinfo['roleid'] == 4) {
            $where['roleid'] = 6;
            $where['puserid'] = $this->uinfo['userid'];
        } elseif ($this->uinfo['roleid'] == 6) {
            $where['userid'] = $this->uinfo['userid'];
        }
        $deallist = model($this->model)->where($where)->order('userid desc')->column('userid, username');
        $this->assign('deallist', $deallist);
        $this->assign('authgroup', cache('AuthGroup'));
        return $this->fetch();
    }

    public function get_renew_user() {
//        $where['status'] = 0;
//        $deallist = model($this->model)->where($where)->where('viprenew' ,'>', 0)->order('userid desc')->select();
        $page = input("param.page", 1);
        $order = input("param.order");
        $limit = input("param.limit", $this->default_page_items);
        $db = model($this->model);
        $offset = ($page - 1) * $limit;
        $whereMap = $this->get_where_map();
        $whereMap['status'] = 0;
        $whereMap['viprenew'] = ['>', 0];
        list($list, $count) = $db->admin_get_list($offset, $limit, $whereMap, $order);
        $return = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $list,
        ];
        return json($return);
    }
	
}
